package com.itheima.service.impl;

import com.itheima.annotion.MyAnnotion;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/7 23:27
 * @Desc:
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;

    //添加部门
    @Override
    @MyAnnotion
    public boolean addDept(String name) {
        if (name == null)
            return false;
        List<Dept> depts = deptMapper.findDeptByName(name);
        if (depts.size() == 0) {
            deptMapper.addDept(name);
            return true;
        }
        return false;
    }

    //删除部门
    @Override
    @MyAnnotion
    @Transactional(rollbackFor = Exception.class)//设置该方法为事务操作，参数为触发事务回滚的条件
    public boolean deleteDept(Integer id) {
        List<Dept> depts = deptMapper.findDeptById(id);

        if (depts.size() != 0) {
            //删除部门信息
            deptMapper.deleteDept(id);
            //删除部门下所有员工信息
            empMapper.deleteByDeptId(id);
            return true;
        }
        return false;
    }

    //修改部门信息
    @Override
    @MyAnnotion
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public boolean updateDept(Integer id, String name) {
        if (name.length() == 0)
            return false;
        List<Dept> depts = deptMapper.findDeptByName(name);

        if (depts.size() == 0 || (id.equals(depts.get(0).getId()))) {
            deptMapper.updateDept(id, name);
            return true;
        }
        return false;
    }

    //查询所有部门
    @Override
    public List<Dept> deptList() {
        List<Dept> depts = deptMapper.deptList();

        return depts;
    }

    //根据id查询部门信息
    @Override
    public List<Dept> findDeptById(Integer id) {
        List<Dept> depts = deptMapper.findDeptById(id);

        return depts;
    }
}
